<?php

namespace App\Model;

class Common
{
    public static function getCurl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public static function postCurl($url, $data = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    /**
     * 随机字符串
     *
     * @param int $length
     * @param bool $numeric
     * @return string
     */
    public static function codeRandom($length = 5 , $numeric = true) {
        if ($numeric) {
            $hash = sprintf('%0'. $length . 'd', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for ($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }

    public static function xml2array($xml)
    {
        $arr = [];
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if (preg_match_all($reg, $xml, $matches)) {
            $count = count($matches[0]);
            for($i = 0; $i < $count; $i++){
                $subXml = $matches[2][$i];
                $key = $matches[1][$i];
                $arr[$key] = preg_match($reg, $subXml) ? self::xml2array($subXml) : $subXml;
            }
        }
        return $arr;
    }

    public static function array2xml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            $str = is_numeric($val) ? $val : "<![CDATA[$val]]>";
            $xml .= "<" . $key . ">" . $str . "</" . $key . ">";
        }
        $xml .= "</xml>";
        return $xml;
    }

    public static function simpleXmlToArray($xml)
    {
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }
}
